package com.joinsdk.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.joinsdk.demo.databinding.ActivityMainBinding;
import com.joinsdk.sdk.ExitListener;
import com.joinsdk.sdk.InitListener;
import com.joinsdk.sdk.JoinSdk;
import com.joinsdk.sdk.PayListener;
import com.joinsdk.sdk.PayParams;
import com.joinsdk.sdk.SdkRole;
import com.joinsdk.sdk.SdkUser;
import com.joinsdk.sdk.UserListener;

import java.util.UUID;

public class MainActivity extends Activity {
    private ActivityMainBinding viewBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());

        restoreSp();

        viewBinding.buttonInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JoinSdk.init(MainActivity.this, "my appId", new InitListener() {
                    @Override
                    public void success() {
                        showMsg("初始化成功");
                    }

                    @Override
                    public void fail(String msg) {
                        showMsg("初始化失败");
                    }
                });
            }
        });

        viewBinding.buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JoinSdk.login(MainActivity.this, new UserListener() {
                    @Override
                    public void loginSuccess(SdkUser user) {
                        showMsg("login success \nuserId=" + user.getUserId() + " token=" + user.getToken());
                    }

                    @Override
                    public void loginFailed() {
                        showMsg("login failed");
                    }

                    @Override
                    public void logout() {
                        showMsg("logout");
                    }
                });
            }
        });

        viewBinding.buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JoinSdk.logout(MainActivity.this);
            }
        });

        viewBinding.buttonPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSp();

                PayParams payParams = new PayParams();
                //必填的字段
                payParams.setOrderId(UUID.randomUUID().toString());
                payParams.setProductId("1");
                payParams.setProductName(getEditTextValue(viewBinding.editTextPayProduct));
                payParams.setProductDesc(getEditTextValue(viewBinding.editTextPayProduct) + "-desc");

                //支付金额单位是人民币分,支付1元填100分
                try {
                    payParams.setMoney(Long.parseLong(getEditTextValue(viewBinding.editTextPayMoney)));
                }catch (Exception e) {
                    payParams.setMoney(0);
                }
                try {
                    payParams.setCount(Long.parseLong(getEditTextValue(viewBinding.editTextPayCount)));
                }catch (Exception e) {
                    payParams.setCount(0);
                }
                payParams.setCallbackUrl(getEditTextValue(viewBinding.editTextPayCallbackUrl));
                payParams.setCallBackInfo(getEditTextValue(viewBinding.editTextPayCallbackInfo));

                //一些渠道发⾏合作关系时必填,其他选填或者忽略
                payParams.setRoleId("1");
                payParams.setRoleName("玩白玩");
                payParams.setRoleLevel("3");
                payParams.setZoneId("1032");
                payParams.setZoneName("奇异果");
                payParams.setVip("55");
                payParams.setBalance("123456");
                payParams.setRatio("10");

                JoinSdk.pay(MainActivity.this, payParams, new PayListener() {
                    @Override
                    public void success(String str) {
                        showMsg("pay success, str=" + str);
                    }

                    @Override
                    public void fail(String str) {
                        showMsg("pay fail, str=" + str);
                    }
                });
            }
        });

        viewBinding.buttonExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JoinSdk.exit(MainActivity.this, new ExitListener() {
                    @Override
                    public void onGameExit() {
                        //渠道不存在退出界面,需要游戏实现退出确认界面,在这里弹出游戏退出对话框
                        showMsg("onGameExit");
                    }

                    @Override
                    public void onChannelExit() {
                        //渠道存在退出界面,无需再弹退出界面,点'确定退出'后执行这里的逻辑
                        showMsg("onChannelExit");
                        System.exit(0);
                    }
                });
            }
        });

        viewBinding.buttonSetRole.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SdkRole role = new SdkRole();
                role.setType(SdkRole.TYPE_ENTER_GAME);
                role.setRoleId("1");
                role.setRoleName("玩白玩");
                role.setRoleLevel("3");
                role.setZoneId("1032");
                role.setZoneName("奇异果");
                role.setVip("55");
                role.setBalance("123456");
                role.setPartyName("小公会");
                role.setExtra("{extra data}");

                JoinSdk.setRole(MainActivity.this, role);
            }
        });

        JoinSdk.onCreate(this);
        Log.d("MainActivity", "channel=" + JoinSdk.getChannel(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        JoinSdk.onStart(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        JoinSdk.onRestart(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JoinSdk.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JoinSdk.onPause(this);
    }

    @Override
    protected void onStop() {
        JoinSdk.onStop(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        JoinSdk.onDestroy(this);
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        JoinSdk.onNewIntent(this, intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        JoinSdk.onBackPressed(this);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        JoinSdk.onConfigurationChanged(this, newConfig);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        JoinSdk.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        JoinSdk.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void restoreSp() {
        SharedPreferences sharedPreferences = getSharedPreferences("app", Activity.MODE_PRIVATE);

        String money = sharedPreferences.getString("pay_money", "1");
        String product = sharedPreferences.getString("pay_product", "全款购");
        String count = sharedPreferences.getString("pay_count", "13");
        String payCallbackUrl = sharedPreferences.getString("pay_back_url", "http://游戏服务器接收支付通知地址");
        String payCallBackInfo = sharedPreferences.getString("pay_back_info", "发送的额外参数abc123");

        viewBinding.editTextPayMoney.setText(money);
        viewBinding.editTextPayProduct.setText(product);
        viewBinding.editTextPayCount.setText(count);
        viewBinding.editTextPayCallbackUrl.setText(payCallbackUrl);
        viewBinding.editTextPayCallbackInfo.setText(payCallBackInfo);
    }

    private void saveSp() {
        SharedPreferences sharedPreferences = getSharedPreferences("app", Activity.MODE_PRIVATE);
        sharedPreferences.edit()
                .putString("pay_money", getEditTextValue(viewBinding.editTextPayMoney))
                .putString("pay_product", getEditTextValue(viewBinding.editTextPayProduct))
                .putString("pay_count", getEditTextValue(viewBinding.editTextPayCount))
                .putString("pay_back_url", getEditTextValue(viewBinding.editTextPayCallbackUrl))
                .putString("pay_back_info", getEditTextValue(viewBinding.editTextPayCallbackInfo))
                .apply();
    }

    public static String getEditTextValue(EditText editText) {
        String result = "";
        if (editText == null)
            return result;
        Editable editable = editText.getText();
        if (editable == null)
            return result;
        return editable.toString().trim();
    }

    private void showMsg(final String msg) {
        if(!TextUtils.isEmpty(msg)) {
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(MainActivity.this)
                            .setMessage(msg)
                            .setCancelable(true)
                            .show();
                }
            });
        }
    }
}